<?php

namespace component\system\system_user;

use common\ApiError;
use common\Common;
use common\logic\Logic;

class SystemUser extends Logic
{

    /**
     * 禁用
     * @var int
     */
    const STATUS_FORBID = 0;

    /**
     * 启用
     * @var int
     */
    const STATUS_OPEN = 1;

    /**
     * @var array
     */
    public $fields = [
        'id',
        'username',
        'nickname',
        'avatar',
        'phone',
        'email',
        'status',
        'create_time',
    ];

    /**
     * @return SystemUserModel|\think\Model
     */
    protected function model()
    {
        return new SystemUserModel();
    }

    /**
     * @param $username
     * @return SystemUserModel
     */
    public function getByUsername($username)
    {
        /**
         * @var SystemUserModel $record
         */
        $record = $this->find(['username' => $username]);

        return $record;
    }

    /**
     * @param $phone
     * @return SystemUserModel|null
     */
    public function getByPhone($phone)
    {
        /**
         * @var SystemUserModel $record
         */
        $record = $this->find(['phone' => $phone]);

        return $record;
    }

    /**
     * @param $username
     * @param $password
     * @return bool|SystemUserModel
     */
    public function login($username, $password)
    {
        $record = $this->setFields(['*'])->getByUsername($username);

        if (empty($record) || empty($password) || $record['password'] != Common::encryptionPassword($password)) {
            ApiError::instance()->message('用户名或密码错误');
            return false;
        }

        if ($record['status'] == self::STATUS_FORBID) {
            ApiError::instance()->message('此用户已被禁止登陆');
            return false;
        }

        unset($record['password']);
        unset($record['delete_time']);

        return $record;
    }

    /**
     * @param int $status
     * @return array|\think\Collection|\think\Paginator
     */
    public function getListByStatus($status = self::STATUS_OPEN)
    {
        $records = $this->select(['status' => $status]);

        return $records;
    }
}